package com.infore.authorityManagement.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.infore.authorityManagement.dto.Menu;
import com.infore.authorityManagement.entity.BusinessConstant;
import com.infore.authorityManagement.entity.SysPermission;
import com.infore.authorityManagement.entity.SysRole;
import com.infore.authorityManagement.enums.ResultStatus;
import com.infore.authorityManagement.service.ISysPermissionService;
import com.infore.authorityManagement.service.ISysRoleService;
import com.infore.authorityManagement.util.MenuTreeUtil;
import com.infore.authorityManagement.util.Page;
import com.infore.authorityManagement.util.ResultEntity;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * @ClassName: RoleController
 * @Description: 角色管理controller类
 * @author 谭红波
 * @date 2017年9月12日
 */
@Api(value = "角色管理", tags = "角色管理")
@Controller
@RequestMapping("/roles")
public class RoleController {
    
    @Autowired
    ISysRoleService roleService;
    
    @Autowired
    ISysPermissionService permissionService;
    

    @ApiOperation(value = "查询角色", notes = "根据角色ID来获取角色详细信息")
    @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, dataType = "String")
    @RequestMapping(value = "/id", method = RequestMethod.GET)
    public @ResponseBody ResultEntity getRoleById(@RequestParam String roleId, String token) {
        SysRole sysRole = roleService.getRoleById(roleId);
        if (sysRole == null) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.ROLE_NOT_EXIST, null);
        }
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.QUERY_SUCCESS).setInfo(sysRole);
    }

    @ApiOperation(value = "查询角色", notes = "批量查询角色,约定：当pageSize小于1 或者 pageNo小于0或者其中一个为空时，不进行分页操作")
    @RequestMapping(value = "", method = RequestMethod.GET)
    public @ResponseBody ResultEntity getRoles(SysRole sysRole, Integer pageSize, Integer pageNo,
            String token) {
        if (pageSize == null || pageNo == null || pageSize < 1 || pageNo < 0) {
            List<SysRole> list = roleService.getRoles(sysRole);
            return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.QUERY_SUCCESS).setDataList(list);
        } else {
            Page<SysRole> page = roleService.getRolesForPage(sysRole, pageSize, pageNo);
            return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.QUERY_SUCCESS).setPage(page);
        }
    }

    @ApiOperation(value = "查询角色", notes = "批量查询角色,约定：当pageSize小于1 或者 pageNo小于0或者其中一个为空时，不进行分页操作")
    @RequestMapping(value = "/parent", method = RequestMethod.GET)
    public @ResponseBody ResultEntity getRolesWidthParent(SysRole sysRole, Integer pageSize, Integer pageNo,
            String token) {
        if (pageSize == null || pageNo == null || pageSize < 1 || pageNo < 0) {
            List<SysRole> list = roleService.getRoles(sysRole);
            return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.QUERY_SUCCESS).setDataList(list);
        } else {
            Page<SysRole> page = roleService.getRolesWidthParent(sysRole, pageSize, pageNo);
            return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.QUERY_SUCCESS).setPage(page);
        }
    }

    @ApiOperation(value = "新增角色", notes = "新增角色信息")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public @ResponseBody ResultEntity addRole(SysRole sysRole, String token) {
        String roleName = sysRole.getRoleName();
        if (roleName == null || "".equals(roleName)) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.PARAM_ERROR);
        }
        Map<String, Object> map = roleService.addRole(sysRole);
        int resultIdt = (int) map.get("resultIdt");
        if (resultIdt == -1) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.ROLE_EXIST);
        }
        if (resultIdt == -2) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.DATA_ERROR);
        }
        if (resultIdt == -4) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.P_ROLE_NOT_EXIST);
        }
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.INSERT_SUCCESS).setMapValue("roleId", map.get("roleId"));
    }

    @ApiOperation(value = "修改角色", notes = "根据角色id修改角色")
    @RequestMapping(value = "", method = RequestMethod.PUT)
    public @ResponseBody ResultEntity updateRole(SysRole sysRole, String token) {
        int resultIdt = roleService.updateRoles(sysRole);
        if (resultIdt == -1) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.ROLE_NOT_EXIST);
        }
        if (resultIdt == -2) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.ROLE_EXIST);
        }
        if (resultIdt == -3) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.DATA_ERROR);
        }
        if (resultIdt == -4) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.P_PERMISSION_NOT_EXIST);
        }
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.UPDATE_SUCCESS);
    }

    @ApiOperation(value = "删除角色", notes = "根据角色id删除角色")
    @RequestMapping(value = "", method = RequestMethod.DELETE)
    public @ResponseBody ResultEntity deleteRoleById(@RequestParam String roleId, String token) {
        int resultIdt = roleService.deleteRoleById(roleId);
        if (resultIdt == -2) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.DELETE_FAILURE);
        }
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.DELETE_SUCCESS);
    }
    
    @ApiOperation(value = "批量删除角色", notes = "根据角色id删除角色")
    @RequestMapping(value = "/ids", method = RequestMethod.DELETE)
    public @ResponseBody ResultEntity batchDeleteRoleByIds(@RequestParam String ids, String token) {
    	if (StringUtils.isEmpty(ids)) {
    		return new ResultEntity(ResultStatus.ERROR, BusinessConstant.PARAM_ERROR);
    	}
    	String[] idArr = ids.split(",");
    	for (int i = 0; i < idArr.length; i++) {
    		int resultIdt = roleService.deleteRoleById(idArr[i]);
            if (resultIdt == -2) {
                return new ResultEntity(ResultStatus.ERROR, BusinessConstant.DELETE_FAILURE);
            }
    	}
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.DELETE_SUCCESS);
    }
    
    @ApiOperation(value = "批量新增角色站点", notes = "批量新增角色站点关联")
    @RequestMapping(value = "/stations/ids", method = RequestMethod.POST)
    public @ResponseBody ResultEntity addRolePermissions(@RequestParam String roleId,
            @RequestParam String stationIds, String token) {
        String[] stationIdsArr = stationIds.split(",");
        int resultIdt = roleService.addRoleStations(roleId, stationIdsArr);
        if (resultIdt == -1) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.ROLE_NOT_EXIST);
        } else if (resultIdt == -2) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.PERMISSION_NOT_EXIST);
        } else if (resultIdt == -3) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.PERMISSION_ROLE_EXIST);
        } else if (resultIdt == -4) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.DATA_ERROR);
        }
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.INSERT_SUCCESS);
    }
    
    @ApiOperation(value = "查询角色站点权限", notes = "查询角色站点权限信息")
    @RequestMapping(value = "/roleStations", method = RequestMethod.GET)
    public @ResponseBody ResultEntity getRoleStations(@RequestParam String roleId, String token) {
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.QUERY_SUCCESS)
                .setDataList(roleService.getRoleStations(roleId));
    }
    
    @ApiOperation(value = "查询角色菜单权限", notes = "查询角色菜单权限信息")
    @RequestMapping(value = "/rolePermissions", method = RequestMethod.GET)
    public @ResponseBody ResultEntity getRolePermissions(@RequestParam String roleId,String appCode, String token) {
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.QUERY_SUCCESS)
                .setDataList(roleService.getRolePermissionMenu(roleId, appCode));
    }
    
    @ApiOperation(value = "批量新增角色权限", notes = "批量新增角色权限关联")
    @RequestMapping(value = "/permissions/ids", method = RequestMethod.POST)
    public @ResponseBody ResultEntity addRolePermissionsArray(@RequestParam String roleId,
            @RequestParam String permissionIds, String token) {
        String[] permissionArray = permissionIds.split(",");
        int resultIdt = roleService.addRolePermissions(roleId, permissionArray);
        if (resultIdt == -1) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.ROLE_NOT_EXIST);
        } else if (resultIdt == -2) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.PERMISSION_NOT_EXIST);
        } else if (resultIdt == -3) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.PERMISSION_ROLE_EXIST);
        } else if (resultIdt == -4) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.DATA_ERROR);
        }
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.INSERT_SUCCESS);
    }
    
    @ApiOperation(value = "查询角色拥有指定系统所有菜单权限信息", notes = "查询角色权限信息，并标识该角色拥有的菜单权限信息")
    @RequestMapping(value = "/permissions/menus/checked", method = RequestMethod.GET)
    public @ResponseBody ResultEntity getAllRoleMenuPermission(String roleId, String appCode) {
        if (StringUtils.isEmpty(roleId) || StringUtils.isEmpty(appCode)) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.PARAM_ERROR);
        }
        
        SysPermission sysPermission = new SysPermission();
        List<SysPermission> allPermission = permissionService.getPermissions(sysPermission);
        
        List<SysPermission> rolePermission = roleService.getRolePermissionMenu(roleId, appCode);
        List<SysPermission> spList = new ArrayList<>();
        for (int k = 0; k < allPermission.size(); k++) {
            SysPermission sp = allPermission.get(k);
            if (sp.getPermissionType() == 0 || !sp.getAppCode().equals(appCode)) {
                continue;
            }
            for (int i = 0; i < rolePermission.size(); i++) {
                SysPermission p = rolePermission.get(i);
                if (p == null) {
                    continue;
                }
                if (sp.getPermissionId().equals(p.getPermissionId())) {
                    sp.setChecked(1);
                }
            }
            spList.add(sp);
        }
        List<Menu> menuList = new ArrayList<>();
        for (SysPermission p : spList) {
            Menu menu = new Menu();
            menu.setId(p.getPermissionId());
            menu.setParentId(p.getPermissionParentID());
            menu.setLevel(p.getPermissionLevel());
            menu.setName(p.getPermissionName());
            menu.setLabel(p.getPermissionName());
            menu.setUrl(p.getUrl());
            menu.setSeqNum(p.getSeqNum());
            menu.setImg(p.getPermissionPictureUrl());
            menu.setType(p.getPermissionType());
            menu.setChecked(p.getChecked());
            menu.setItemChecked(p.getChecked());
            menu.setDescription(p.getDescription());
            menu.setStatus(p.getStatus());
            menu.setDisabled(p.getChecked() == 1?true:false);
            menuList.add(menu);
        }
        List<Menu> list = MenuTreeUtil.getTree(menuList);
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.QUERY_SUCCESS).setDataList(list);
    }

  
}
